import Log from "../utils/log";
import FileTypes from "./file_types";
import { Message } from "element-ui";
import GraphicManager from "../mev/draw/core/GraphicManager";
import MarkerManager from "../mev/draw/core/MarkerManager";

window.JsContext = (function() {
    function JsContext() {}

    JsContext.Log = Log;

    JsContext.slotSelectGpsFile = function(filepath) {
        Message.error(`${filepath}`);
    };

    JsContext.onFileBrowserLoaded = function(id, isFile, filepath) {
        switch (id) {
            case FileTypes.GEO_JSON.id: {
                if (isFile === FileTypes.GEO_JSON.file) {
                    // do here
                    Message.success(`${id}, ${isFile}, ${filepath}`);
                }
                break;
            }

            case FileTypes.GPS.id: {
                if (isFile === FileTypes.GPS.file) {
                    Message.info(`${id}, ${isFile}, ${filepath}`);
                } else {
                    Message.error(`${id}, ${isFile}, ${filepath}`);
                }
            }
        }
    };

    JsContext.onGeoJsonFileLoaded = function(filepath) {
        Message.success(`${filepath}`);
    };

    JsContext.onMarkGeoJsonExport = function(folder) {
        const json = {
            type: "FeatureCollection",
            name: "graphic",
            crs: {
                type: "name",
                properties: { name: "urn:ogc:def:crs:OGC:1.3:CRS84" }
            },
            features: []
        };
        let managers = GraphicManager.INSTANCE.manager.values();
        for (let m of managers) {
            console.log(m);
            json.features.push(m.toGeoJson());
        }
        managers = MarkerManager.INSTANCE.manager.values();
        for (let m of managers) {
            console.log(m);
            json.features.push(m.toGeoJson());
        }

        let filepath = folder + "/标注_" + new Date().formatPure() + ".geojson";
        JavaContext.write(filepath, JSON.stringify(json, null, 2));
    };

    JsContext.onMarkGeoJsonImport = function(filename) {
        Message.info("load " + filename);
        const obj = JSON.parse(JavaContext.read(filename));
        obj.features.forEach(feature => {
            if (feature.geometry.type.toUpperCase() === "LineString".toUpperCase() || feature.geometry.type.toUpperCase() === "POLYGON") {
                GraphicManager.INSTANCE.import(feature);
            } else if (feature.geometry.type.toUpperCase() === "POINT") {
                MarkerManager.INSTANCE.import(feature);
            }
        });
    };

    return JsContext;
})();
